package com.fancy.mobileschool.ui;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fancy.mobileschool.MyConfiguration;
import com.fancy.mobileschool.R;
import com.fancy.mobileschool.cache.ChatMessageCache;
import com.fancy.mobileschool.entity.PersonChatMessage;
import com.fancy.mobileschool.service.ChatFriendsService;
import com.fancy.mobileschool.task.TaskExecutor;
import com.fancy.mobileschool.ui.adapt.ChatPersonMessageAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ChatPersonRoomActivity extends AppCompatActivity implements View.OnClickListener, TextView.OnEditorActionListener{

    private final int getConversationMsg = 1;

    private final int sendMessageMsg = 2;

    private final int refreshMessage = 3;

    private final int sendMessageMsgError = 4;

    private TextView textView;

    private ImageView back;

    private Lock lock = new ReentrantLock();

    private ChatMessageCache chatMessageCache;

    private volatile boolean run = true;

    private String friendID;

    private String friendName;

    private ChatFriendsService chatFriendsService = new ChatFriendsService();

    private RecyclerView recyclerView;

    private ChatPersonMessageAdapter adapter;

    private List<PersonChatMessage> messages = new ArrayList<>();

    private EditText editText;

    private Button sendButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_room);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.custom_action_bar);
        }

        recyclerView = (RecyclerView) findViewById(R.id.chat_room_message_recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        editText = (EditText) findViewById(R.id.input);
        sendButton = (Button) findViewById(R.id.send_button);
        textView = (TextView) findViewById(R.id.textView);
        back = (ImageView) findViewById(R.id.back);

        friendID = getIntent().getStringExtra("friendID");
        friendName = getIntent().getStringExtra("friendName");
        textView.setText(friendName);

        assert sendButton != null;
        sendButton.setOnClickListener(this);
        back.setOnClickListener(this);
        editText.setOnEditorActionListener(this);

        //initConversation();
    }

    @Override
    protected void onStart() {
        super.onStart();
        chatMessageCache = new ChatMessageCache(this, "chat1", null, 1);
        initConversation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        run = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        run = true;
        startRefreshService();
    }

    @Override
    protected void onStop() {
        super.onStop();
        chatMessageCache.freed();
    }

    private void startRefreshService() {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                while (run){
                    List<PersonChatMessage> notReadMessage = chatFriendsService.getNotReadMessage(MyConfiguration.myID, friendID);
                    lock.lock();
                    if (notReadMessage != null && notReadMessage.size() > 0){
                        chatMessageCache.insertMessage(notReadMessage);
                        for (int i = 0 ; i<notReadMessage.size() ; i++) {
                            adapter.addMessage(notReadMessage.get(i));
                        }
                        Message message = handler.obtainMessage();
                        message.arg1 = notReadMessage.size();
                        message.what = refreshMessage;
                        handler.sendMessage(message);
                    }
                    lock.unlock();

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        });

    }

    private void initConversation() {
        TaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                lock.lock();
//                messages = chatFriendsService.getMyConversation(MyConfiguration.myID, friendID);
//                if (messages != null){
//                    adapter = new ChatPersonMessageAdapter(ChatPersonRoomActivity.this, messages);
//                    handler.sendEmptyMessage(getConversationMsg);
//                }
                messages = chatMessageCache.getConversation(MyConfiguration.myID, friendID);
                if (messages != null){
                    Collections.sort(messages);
                    adapter = new ChatPersonMessageAdapter(ChatPersonRoomActivity.this, messages);
                    handler.sendEmptyMessage(getConversationMsg);
                }
                lock.unlock();
            }
        });
    }


    private  Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == getConversationMsg) {
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                recyclerView.scrollToPosition(adapter.getItemCount() - 1);
            }else if (msg.what == sendMessageMsg) {
                adapter.notifyDataSetChanged();
                recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                editText.setText("");
            }else if (msg.what == refreshMessage) {
                if (isVisBottom(recyclerView, msg.arg1) || editText.isActivated()) {
                    adapter.notifyDataSetChanged();
                    recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
                }else
                    adapter.notifyDataSetChanged();

            }else if (msg.what == sendMessageMsgError){
                Toast.makeText(ChatPersonRoomActivity.this, "发送信息失败", Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.send_button){
            TaskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    sendMessage();
                }

            });
        }else if (view.getId() == R.id.back) {
            finish();
        }
    }

    @Override
    public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
//        if (i == 0) {
//            TaskExecutor.execute(new Runnable() {
//                @Override
//                public void run() {
//                  //sendMessage();
//                }
//
//            });
//        }

        return true;
    }

    private void sendMessage() {
        String content = editText.getText().toString();
        if (!content.equals("")&& !(editText == null) ){
            PersonChatMessage message = new PersonChatMessage(MyConfiguration.myID, friendID, content, null);
            PersonChatMessage result = chatFriendsService.sendMessage(message);
            if (result != null){
                adapter.addMessage(message);
                chatMessageCache.insertMessage(message);
                handler.sendEmptyMessage(sendMessageMsg);
            }else {
                handler.sendEmptyMessage(sendMessageMsgError);
            }
        }
    }

    private  boolean isVisBottom(RecyclerView recyclerView, int newAddCount){
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        Log.i("wode", lastVisibleItemPosition + "最后一个");
        int visibleItemCount = layoutManager.getChildCount();
        int totalItemCount = layoutManager.getItemCount();
        Log.i("wode", totalItemCount + "总共");
        if(visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 - newAddCount){
            return true;
        }else {
            return false;
        }
    }
}
